<template>
    <div class="noPayDetails-view">

      <modules-title titleName="收费详情">

        <template slot="other">
          <div class="priceView">
            <div class="priceView-item">
              <span>总金额：¥{{total.toFixed(2)}}</span>
            </div>

            <div class="priceView-item">
              <span>优惠 ¥</span>
              <el-input v-model="preferentialValue" placeholder="请输入" @keyup.native="proving" @blur="inputBlur"></el-input>
            </div>

            <div class="priceView-item">
              <span>应收：</span>
              <span class="price">¥{{amount.toFixed(2)}}</span>
            </div>
          </div>
        </template>
        <template slot="btn">
          <el-button class="main-btn" type="primary" @click="payClick">收费</el-button>

          <el-checkbox v-model="checked">打印小票</el-checkbox>

          <el-button class="border-btn" @click="printPrescri">打印处方</el-button>

<!--          <el-button class="border-btn" @click="printBill">打印小票</el-button>-->

          <el-button class="border-btn" @click="backClick">返回</el-button>
        </template>
      </modules-title>

      <div class="scroll-view">

        <div class="patientView">

          <div class="title">诊断详情</div>

          <div class="bese-information">
            <div class="information-item">
              <span class="grayTitle">患者：</span>
              <span class="value">{{datas.real_name}}</span>
            </div>

            <div class="information-item">
              <span class="grayTitle">性别：</span>
              <span class="value" v-if="datas.gender == '0'">男</span>
              <span class="value" v-else-if="datas.gender == 1">女</span>
            </div>

            <div class="information-item">
              <span class="grayTitle">年龄：</span>
              <span class="value">{{datas.age | dealAge}}</span>
            </div>

            <div class="information-item">
              <span class="grayTitle">医生：</span>
              <span class="value">{{datas.doctor_name}}</span>
            </div>

            <div class="information-item" v-if="datas.department_name && datas.department_name != ''">
              <span class="grayTitle">科室：</span>
              <span class="value">{{datas.department_name}}</span>
            </div>

            <div class="information-item">
              <span class="grayTitle">就诊日期：</span>
              <span class="value" >{{datas.created_at}}</span>
            </div>

            <div class="information-item">
              <span class="grayTitle">就诊类型：</span>
              <span class="value" v-if="datas.medical_record_repeat == 2">复诊</span>
              <span class="value" v-else-if="datas.medical_record_repeat == 1">初诊</span>
              <span class="value" v-else>无</span>
            </div>
          </div>

          <div class="total-view">
            <div class="information-item">
              <span class="grayTitle">诊断：</span>
              <span class="value">{{datas.result}}</span>
            </div>
          </div>
        </div>

        <check-item v-if="datas.check_item  && datas.check_item.length > 0" :datas="datas.check_item" :type="type" @dataChange="checkChange"></check-item>

        <surcharge-item v-if="datas.surcharge  && datas.surcharge.length > 0" :datas="datas.surcharge" :type="type" @dataChange="surchargeChange"></surcharge-item>

        <prescription-item v-for="i in datas.prescription_ary_info" :method="datas.sell_method" :data="i" v-model="i.details" :type="type" @dataChange="prescriptionChange"></prescription-item>

      </div>

      <pay-dialog ref="payDialog" @pay-confirm="payConfirm"></pay-dialog>

      <print ref="print"></print>

    </div>
</template>

<script>
  import print from "../../print/print";
  import surchargeItem from "../modules/surchargeItem";
  import checkItem from "../modules/checkItem";
  import {medicinePayDetail,medicineCharge} from "../../../api/payOrDrug";
  import payDialog from "../modules/payDialog";
    import prescriptionItem from "../modules/prescriptionItem";

    export default {
        name: "index",
        components:{prescriptionItem,payDialog,checkItem,surchargeItem,print},
        data:function () {
            return{
                type:1,
                value:'',
                checked:false,

                preferentialValue:0,
                payDialog:null,
                datas:{
                    amount:0,
                    created_at:'',
                },
                payDatas:{},
                total:0,
                caseHistoryDetail:{}
            }
        },
        computed: {
            amount: function(){//test为计算属性，调用时和调用属性一样调用test即可
                let am = 0;
                am = this.total - this.preferentialValue;
                return am//msg是依赖属性，改变时会执行test函数
            }
        },
        mounted:function(){
            if (this.$route.query.id){
                this.getData(this.$route.query.id)
            }
            this.payDialog = payDialog;
        },
        methods:{
            payConfirm:function(data){
                this.payDatas.id = this.payDatas.charge_id
                this.payDatas.option_type = 1;
                this.payDatas.pay_type = Number(data.pay_type)
                this.payDatas.receipts_amount = Number(this.amount)
                this.payDatas.auth_code = data.auth_code

                let num = 0;
                let price = 0;
                let list = [];
                for (let i = 0; i < this.payDatas.prescription_ary_info.length; i++){
                    let data = this.payDatas.prescription_ary_info[i];

                    if (data.details.length > 0){
                        for (let j = 0; j < data.details.length; j++){
                            let amount = data.details[j].number*data.details[j].price;
                            data.details[j].amount = amount;
                            num += data.details[j].number;
                            price += amount;
                        }
                        list.push(data)
                    }
                }

                this.payDatas.prescription_ary_info = list;

                for (let i = 0; i < this.payDatas.surcharge.length; i++){
                    this.payDatas.surcharge[i].surcharge_number = 1;
                    num ++;
                    price += this.payDatas.surcharge[i].amount;
                }

                for (let i = 0; i < this.payDatas.check_item.length; i++){
                    this.payDatas.check_item[i].check_item_status = 2;
                    num += this.payDatas.check_item[i].check_item_number;
                    price += this.payDatas.check_item[i].check_item_number*this.payDatas.check_item[i].price;
                }

                let num2 = 0;
                for (let i = 0; i < this.datas.prescription_ary_info.length; i++){
                    let data = this.datas.prescription_ary_info[i];

                    for (let j = 0; j < data.details.length; j++){
                        num2 += data.details[j].number;
                    }
                }

                for (let i = 0; i < this.datas.check_item.length; i++){
                    num2 += this.datas.check_item[i].check_item_number;
                }

                for (let i = 0; i < this.datas.surcharge.length; i++){
                    num2 ++;
                }

                this.payDatas.is_finish_charge = num == num2 ? 2 : 1;

                this.payDatas.amount = price;
                let status = 1;
                if (this.$store.getters.systemSetting.dic_value){
                    let obj = JSON.parse(this.$store.getters.systemSetting.dic_value);
                    status = Number(!obj.charge_dispensing_management.function_set)
                }
                this.payDatas.status = status;

                const loading = this.$loading({
                    lock: true,
                    text: 'Waiting',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });

                medicineCharge(this.payDatas).then((res)=>{
                    loading.close();
                    if (res.code == 200){
                        this.$message({
                            message: '付款成功',
                            type: 'success'
                        });
                        if (this.checked){
                            this.printBill(this.payDatas);
                            setTimeout(()=>{
                                this.$router.replace({name:"noPayList",query:{t:new Date().getTime()}})
                            },1000)
                        }else {
                            this.$router.replace({name:"noPayList",query:{t:new Date().getTime()}})
                        }

                        // this.$router.back();
                    }else {
                        this.$message.error(res.msg);
                    }
                }).catch((err)=>{
                    loading.close();
                })
            },
            payClick:function () {
                let pay = false;
                for (let i = 0; i < this.payDatas.prescription_ary_info.length; i++){
                    let data = this.payDatas.prescription_ary_info[i];

                    for (let j = 0; j < data.details.length; j++){
                        pay = true;
                    }
                }
                for (let i = 0; i < this.payDatas.surcharge.length; i++){
                    pay = true;
                }
                for (let i = 0; i < this.payDatas.check_item.length; i++){
                    pay = true;
                }
                if (!pay){
                    this.$message.error("请选择付费对象");
                    return;
                }
                this.$refs["payDialog"].openDialog({receipts_amount:this.amount})
            },
            getData:function (id) {
                medicinePayDetail(id).then((res)=>{
                    if (res.code == 200){

                        // for (let i = 0; i < res.data.prescription_ary_info.length; i++){
                        //     let data = res.data.prescription_ary_info[i]
                        //     for (let j = 0; j < data.details.length; j++){
                        //         let a = JSON.stringify(data.details[j].number)
                        //         data.details[j].refundNum = JSON.parse(a);
                        //     }
                        // }
                        this.datas = res.data;
                        this.payDatas = {...this.datas}
                        this.payDatas.prescription_ary_info = [];
                        this.payDatas.check_item = [];
                        this.payDatas.surcharge = [];
                    }
                })
            },
            prescriptionChange:function (list) {
                console.log("prescriptionChange")
                console.log(list);
                let index = -1;
                for (let i = 0; i < this.payDatas.prescription_ary_info.length; i++){
                    if (this.payDatas.prescription_ary_info[i].id == list.id){
                        index = i;
                    }
                }
                if (index != -1){
                    this.payDatas.prescription_ary_info[index] = list;
                }else {
                    this.payDatas.prescription_ary_info.push(list);
                }

                this.totalChange();
            },
            checkChange:function(list){
                this.payDatas.check_item = list;

                this.totalChange();
            },
            surchargeChange:function(list){
                this.payDatas.surcharge = list;

                this.totalChange();
            },
            totalChange:function(){
                this.preferentialValue = 0;
                let num = 0;
                for (let i = 0; i < this.payDatas.prescription_ary_info.length; i++){
                    let data = this.payDatas.prescription_ary_info[i];

                    for (let j = 0; j < data.details.length; j++){
                        num += data.details[j].number*data.details[j].price;
                    }
                }

                for (let i = 0; i < this.payDatas.check_item.length; i++){
                    num += this.payDatas.check_item[i].check_item_number*this.payDatas.check_item[i].price;
                }

                for (let i = 0; i < this.payDatas.surcharge.length; i++){
                    num += this.payDatas.surcharge[i].amount;
                }

                this.total = num;
            },
            inputBlur:function(){
                this.preferentialValue = Number(this.preferentialValue).toFixed(2)
            },
            proving:function() {
                let str = this.preferentialValue
                // this.form.skus[e].Price 是input的值　　
                // 先把非数字的都替换掉，除了数字和.
                str = str.replace(/[^\d.]/g, '');
                // 必须保证第一个为数字而不是.
                str = str.replace(/^\./g, '');
                // 保证只有出现一个.而没有多个.
                str = str.replace(/\.{2,}/g, '');
                // 保证.只出现一次，而不能出现两次以上
                str = str.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
                let index = -1
                for (let i in str) {
                    if (str[i] === '.') {
                        index = i
                    }
                    if (index !== -1) {
                        if (i - index > 2) {
                            str = str.substring(0, str.length - 1)
                        }
                    }
                }
                if (Number(str) > this.total){
                    str = this.total
                }
                this.preferentialValue = str;

            },
            backClick:function () {
                this.$router.back()
            },
            printPrescri:function () {
                this.caseHistoryDetail = {...this.datas};
                this.caseHistoryDetail.prescriptions = this.caseHistoryDetail.prescription_ary_info;
                this.caseHistoryDetail.check_items = this.caseHistoryDetail.check_item;

                let pay = false;
                let data = {...this.payDatas}
                data.prescriptions = [];
                for (let i = 0; i < this.payDatas.prescription_ary_info.length; i++){
                    let a = this.payDatas.prescription_ary_info[i];

                    if (a.details.length > 0){
                        pay = true;
                        data.prescriptions.push(a)
                    }

                }
                if (this.payDatas.surcharge.length > 0){
                    pay = true;
                }
                if (this.payDatas.check_item.length > 0){
                    pay = true;
                }

                if (!pay){
                    this.$message.error("请选择付费对象");
                    return;
                }

                data.receipts_amount = this.amount;
                data.ID = data.medical_record_id;
                data.medical_repeat = data.medical_record_repeat

                // data.prescriptions = data.prescription_ary_info
                data.check_items = data.check_item

                this.$refs.print.printPrescription(data)
                // setTimeout(()=>{
                //     this.$refs.prescriptionPrint.print()
                // },500)

            },
            printBill:function (payDatas) {
                let amount = 0;
                let list = []
                for (let i = 0; i < payDatas.prescription_ary_info.length; i++){
                    let data = payDatas.prescription_ary_info[i];

                    if (data.details.length > 0){
                        for (let j = 0; j < data.details.length; j++){
                            amount += data.details[j].number*data.details[j].price
                        }
                        list.push(data)
                    }
                }
                for (let i = 0; i < payDatas.surcharge.length; i++){
                    amount+=payDatas.surcharge[i].amount
                }
                for (let i = 0; i < payDatas.check_item.length; i++){
                    amount+=payDatas.check_item[i].check_item_number*payDatas.check_item[i].price
                }

                let data = {...payDatas}
                data.prescription_ary_info = list;
                data.receipts_amount = this.amount;
                data.amount = amount;
                data.created_at = this.dealDate(new Date());
                data.user_name = this.$store.getters.userInfo.real_name
                this.$refs.print.printBill(data)
            },
            dealDate:function (date) {
                let year = date.getFullYear();
                let month = date.getMonth() + 1;
                let day = date.getDate();
                if (month < 10){
                    month = "0" + month
                }
                if (day < 10){
                    day = "0" + day;
                }

                let hour = date.getHours();
                let minute = date.getMinutes();
                let second = date.getSeconds();

                if (minute < 10){
                    minute = "0" + minute
                }

                if (second < 10){
                    second = "0" + second
                }

                return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
            },
        }
    }
</script>

<style lang="scss" scoped>
  @import "@/assets/scss/payOrDrug/noPayDetails.scss";
</style>
